<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--考核汇总-->
      <!-- <el-col :span="4" :xs="5">
        <treeIndex :deptOptions="deptOptions" @handleNode="handleNodeClick" :title="'部门信息'"></treeIndex>
      </el-col> -->
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          label-width="90px"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
        >
          <el-col :span="6">
            <el-form-item label="院系">
              <el-select
                v-model="queryParams.deptId"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in classTreeList"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="辅导员工号">
              <el-input
                v-model="queryParams.clrTno"
                placeholder="请输入辅导员工号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="辅导员姓名">
              <el-input
                v-model="queryParams.clrName"
                placeholder="请输入辅导员姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次名称">
              <el-select
                v-model="queryParams.batchId"
                clearable
                placeholder="请选择批次名称"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in cebTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="等级">
              <el-select
                v-model="queryParams.rank"
                clearable
                placeholder="请选择等级"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.clr_sum_rank"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
         
            <el-form-item label="学年">
              <el-date-picker
                v-model="dateRange"
                value-format="yyyy-MM"
                type="monthrange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
      

          <el-col :span="6" style="float: right; text-align: right">
            <el-form-item>
              <div>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="onSearch"
                  size="mini"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh"
                  size="mini"
                  @click="onReset"
                  >重置</el-button
                >
              </div>
            </el-form-item>
          </el-col>
        </el-form>
        <!-- <searchForm
          :formOptions="formOptions"
          @onSearch="onSearch"
          @onReset="onReset"
          :formLabelWidth="formLabelWidth"
          v-show="showSearch"
        /> -->

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['clr:checkrecord:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="upload.open = true"
              v-hasPermi="['clr:checkrecord:import']"
              >批量导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['clr:checkrecord:export']"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['clr:checkrecord:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          :data="list"
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column
            label="学年"
            align="center"
            prop="startEndAmcYear"
            show-overflow-tooltip
          />
          <el-table-column
            label="批次名称"
            align="center"
            prop="batchName"
            show-overflow-tooltip
          />
          <!-- <el-table-column label="批次年级" align="center" prop="gradeField">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.clr_grade_type" :value="scope.row.gradeField" />
            </template>
          </el-table-column> -->
          <el-table-column
            label="辅导员工号"
            align="center"
            prop="clrTno"
            show-overflow-tooltip
          />
          <el-table-column
            label="辅导员名称"
            align="center"
            prop="clrName"
            show-overflow-tooltip
          />
          <el-table-column
            label="所在院系"
            align="center"
            prop="collegeName"
            show-overflow-tooltip
          />

          <el-table-column label="等级" align="center" prop="checkLevel">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.clr_sum_rank"
                :value="scope.row.checkLevel"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="总分数"
            sortable
            align="center"
            prop="score"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['clr:checkrecord:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['clr:checkrecord:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <el-dialog
      title="excel导入"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      批次名称：<el-select
        v-model="batchId"
        clearable
        placeholder="请选择"
        style="margin-bottom: 10px"
      >
        <el-option
          v-for="dict in cebTypeList"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        ></el-option>
      </el-select>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :data="{ batchId }"
        :on-progress="handleFileUploadProgress"
        :on-success="onSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox
              v-model="upload.updateSupport"
            />是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="templateDownload"
            v-hasPermi="['clr:checkrecord:view']"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="导入成功或失败提示信息"
      :visible.sync="uploadData"
      width="500px"
      append-to-body
    >
      <el-descriptions :column="1">
        <el-descriptions-item label="上传总数据"
          >{{ importData.totalSize }}条</el-descriptions-item
        >
        <el-descriptions-item label="成功数据"
          >{{ importData.successSize }}条</el-descriptions-item
        >
        <el-descriptions-item label="失败数据"
          >{{ importData.errorSize }}条</el-descriptions-item
        >
        <el-descriptions-item label="失败原因">
          <!-- <span v-html="studenData.failureMsg"></span> -->
          {{ importData.errorMsg }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadData = false">取 消</el-button>
        <el-button type="primary" @click="uploadData = false">确 定</el-button>
      </span>
    </el-dialog>
    <batchAdd
      ref="addplanRef"
      @onSearch="onSearch"
      :list="cebTypeList"
    ></batchAdd>
  </div>
</template>

<script>
import {
  checkrecordList,
  summary,
  importTemplate,
  delCheckrecord,
  exportCheckrecord,
} from "@/api/clr/statistics";
import searchForm from "@/components/Search/searchForm.vue";
import UploadFile from "./component/uploadFile.vue";

import { getDicts } from "@/api/system/dict/type";
import { getSelector } from "@/api/clr/batch";
import batchAdd from "./component/batchAdd.vue";
import { collegeSelect } from "@/api/information/studentInfor";
import { getToken } from "@/utils/auth";

export default {
  dicts: [
    "clr_grade_type", // 年级批次
    "clr_sum_rank", // 等级
  ],
  components: {
    // treeIndex,
    searchForm,
    UploadFile,
    batchAdd,
  },
  data() {
    return {
      dateRange:[],
      formLabelWidth: "85px",
      total: 0,
      loading: false,
      yearStr: {},
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/clr/checkrecord/importScore",
      },
      batchId: "",
      uploadData: false, // 提示信息弹框
      importData: {}, //提示返回值：
      classTreeList: [],
      formOptions: [
        {
          label: "院系",
          prop: "deptId",
          element: "el-select",
          options: [],
          placeholder: "请选择院系",
        },
        {
          label: "辅导员工号",
          prop: "clrTno",
          element: "el-input",
          placeholder: "请输入辅导员工号",
        },
        {
          label: "辅导员姓名",
          prop: "clrName",
          element: "el-input",
          placeholder: "请输入辅导员姓名",
        },
        {
          label: "批次名称",
          prop: "batchId",
          element: "el-select",
          options: [],
          placeholder: "请输入批次名称",
          initValue: "",
        },
        {
          label: "等级",
          prop: "rank",
          element: "el-select",
          options: [],
          placeholder: "请选择等级",
        },
        {
          label: "学年",
          prop: "amcYears",
          type: "monthrange",
          element: "el-date-picker",
          placeholder: "请选择学年",
          valueFormat: "yyyy-MM",
        },
      ],
      queryParams: {},
      list: [],
      scoreData: {},
      open: false,
      single: true,
      title: "",
      // 显示搜索条件
      showSearch: true,
      deptOptions: [],
      cebTypeList: [],
      exprotDate: "",
      ids: [],
      name: "",
      // 非多个禁用
      multiple: true,
    };
  },
  created() {
    this.department();
    this.getList();
    getDicts("clr_sum_rank").then((res) => {
      this.formOptions[4].options = res.data.map((item) => {
        return {
          value: item["dictValue"],
          label: item["dictLabel"],
        };
      });
    });

    getSelector({ cebType: "A" }).then((res) => {
      this.cebTypeList = this.formOptions[3].options = res.data.map((item) => {
        return {
          value: item["CEBID"],
          label: item["BATCHNAME"],
        };
      });
    });
  },
  methods: {
    // 获取搜索表单提交的数据
    onSearch(val) {
      console.log(val);
      if (val == undefined) {
        this.queryParams = Object.assign(this.queryParams, val);
        this.queryParams.pageNum = 1;
        this.getList();
      } else {
        if (val.amcYears) {
          val.startAmcYear = val.amcYears[0];
          val.endAmcYear = val.amcYears[1];
        }
        this.queryParams = Object.assign(this.queryParams, val);
        this.queryParams.pageNum = 1;
        this.getList();
      }
      // 查询条件和分页数据合并
    },
    // 重置
    onReset(data) {
      data.startAmcYear = undefined;
      data.endAmcYear = undefined;
      this.queryParams.pageNum = 1;
      this.queryParams.deptId = "";
      this.queryParams = Object.assign(this.queryParams, data);
      this.getList();
    },
    onExport(data) {
      this.queryParams = Object.assign(this.queryParams, data);
      console.log(this.queryParams, data, "Daochu");
    },
    // 点击确定上传文件按钮
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 修改
    handleUpdate(row) {
      row = JSON.parse(JSON.stringify(row));
      console.log(row, "xiugai");
      this.$refs.addplanRef.open("edit", row);
    },
    // 获取部门信息
    async department() {
      await collegeSelect().then((res) => {
        // this.deptOptions = res.data;
        this.classTreeList = res.data;
        // this.formOptions[0].options = res.data.map((item) => {
        //   return {
        //     value: item.deptId,
        //     label: item.deptName,
        //   };
        // });
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.cesrIds);
      this.name = selection.map((item) => item.clrName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
     // 导出操作
    handleExport() {
      if (!this.queryParams.batchId) {
        this.$message.error("请选择批次名称");
      } else {
        exportCheckrecord(this.queryParams).then((response) => {
          // console.log(response, "模板下载");
          this.saveAs(
            new Blob([response], {
              type: "application/vnd.ms-excel;charset=utf-8",
            }),
            `考核汇总表${new Date().getFullYear()}-${
              new Date().getMonth() + 1
            }-${new Date().getDate()}`
          );
        });
      }

      // exportCheckrecord
      // // summaryExport().then(res => {
      // //   console.log(res,'export')
      // // })
      // this.download(
      //   "/clr/checkrecord/export",
      //   {
      //     ...this.queryParams,
      //   },
      //   `考核汇总表${new Date().getFullYear()}-${
      //     new Date().getMonth() + 1
      //   }-${new Date().getDate()}.xlsx`
      // );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.cesrId || this.ids;
      console.log(roleIds, "ddd");
      this.name = row.clrName || this.name;
      this.$modal
        .confirm('是否确认删除辅导员姓名"' + this.name + '"的数据项？')
        .then(function () {
          return delCheckrecord(roleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleAdd() {
      this.$refs.addplanRef.open("add");
    },
    //文件上传成功
    onSuccess(response) {
      if (response.code == 200) {
        this.$message.success("文件上传成功");
        this.$refs.upload.clearFiles();
        this.getList();
        this.importData = response.data;
        this.upload.open = false;
        this.upload.isUploading = false;
        this.uploadData = true;
      } else {
        if (response.data) {
          this.importData = response.data;
          this.$message.error("文件上传失败");
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.upload.open = false;
          this.uploadData = true;
        } else {
          this.importData = response.data;
          this.$message.error("文件上传失败");
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.upload.open = false;
        }

        // this.getList();
      }
    },
    // tree树形选中的值
    handleNodeClick(data) {
      console.log(data, "选中的值");
      this.queryParams.deptId = data.id;
      this.getList();
    },
    getList() {
      checkrecordList(this.addDateRange(this.queryParams, this.dateRange)).then((res) => {
        this.list = res.rows;
        this.total = res.total;

        console.log(res, "summary");
      });
    },

    details(row) {
      summary(row.cemId).then((res) => {
        console.log(res, "123");
        if (res.code == 200) {
          this.scoreData = res.data;
          // this.scoreData.scoreList = res.data.classifySummaryList;
          this.title = "辅导员工作考核得分表";
          this.open = true;
        }
      });
    },
    saveAs(obj, fileName) {
      let ele = document.createElement("a");
      ele.download = fileName || "下载"; //下载文件名
      ele.href = URL.createObjectURL(obj); // 绑定a标签
      ele.style.display = "none";
      document.body.appendChild(ele); // 兼容火狐浏览器
      ele.click();
      setTimeout(function () {
        // 延时释放
        URL.revokeObjectURL(obj); // 用 URL.revokeObjectURL() 来释放这个object URL
        document.body.removeChild(ele); // 兼容火狐浏览器
      }, 100);
    },
    // 模板下载
    templateDownload() {
      if (!this.batchId) {
        this.$message.error("请选择批次名称");
      } else {
        importTemplate({ batchId: this.batchId }).then((response) => {
          // console.log(response, "模板下载");
          this.saveAs(
            new Blob([response], {
              type: "application/vnd.ms-excel;charset=utf-8",
            }),
            `考核分数录入模板${new Date().getFullYear()}-${
              new Date().getMonth() + 1
            }-${new Date().getDate()}`
          );
        });
      }
    },
  },
};
</script>

<style>
</style>